package com.qiuguo.rtsp.service;

import com.github.kokorin.jaffree.ffmpeg.FFmpegResultFuture;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Data
@Slf4j
public class StreamTask {
    public enum TaskStatus {
        PROBING,     // 探测中
        RUNNING,     // 运行中
        STOPPED      // 已停止
    }
    
    private String outPutDir;
    private FFmpegResultFuture future;
    private String taskId;
    private String rtspUrl;
    private volatile TaskStatus status = TaskStatus.PROBING; // 默认状态为探测中
    
    public StreamTask(String taskId, String outPutDir, String rtspUrl) {
        this.taskId = taskId;
        this.outPutDir = outPutDir;
        this.rtspUrl = rtspUrl;
        cleanupSegmentFiles();
    }

    public boolean stop() {
        this.setStatus(TaskStatus.STOPPED);
        
        // 取消任务future（如果存在且未完成）
        cleanupSegmentFiles();
        return true;
    }

    /**
     * 设置任务为运行状态
     */
    public void setRunning() {
        this.status = TaskStatus.RUNNING;
    }

    /**
     * 清理指定文件名的片段文件
     *
     */
    public void cleanupSegmentFiles() {
        try {

            if (future != null && !future.isDone()) {
//            cancelled = future.cancel(true);
                future.graceStop();
                future.toCompletableFuture().join();
            }
            Path outputDir = Paths.get(outPutDir);
            if (Files.exists(outputDir)) {
                Files.list(outputDir)
                        .filter(path -> {
                            log.info("path: {}, taskId :{}", path.toString(), taskId);
                            return path.toString().contains(taskId);
                        })
                        .forEach(path -> {
                            try {
                                log.info("已删除文件: {}", path.toString());
                                Files.deleteIfExists(path);
                                log.info("已删除文件: {}", path.getFileName());
                            } catch (IOException e) {
                                log.warn("删除文件失败: {}", path.getFileName(), e);
                            } catch (Exception e) {
                                log.warn("删除文件失败: {}", path.getFileName(), e);
                            }
                        });
                log.info("清理完成，文件名: {}", taskId);
            }
        } catch (IOException e) {
            log.error("IOException 清理文件时发生异常", e);
        } catch (Exception e) {
            log.error("Exception 清理文件时发生异常", e);
        }
    }
}